import 'package:flutter/material.dart';
import 'package:hong_vpn_new_20240626/ui/chat/chat.dart';
import 'package:hong_vpn_new_20240626/ui/home/ai_details.dart';
import 'package:hong_vpn_new_20240626/ui/index/index.dart';
import 'package:hong_vpn_new_20240626/ui/qr/scan_qr.dart';
import 'package:hong_vpn_new_20240626/utils/Configs/ai_config.dart';
import 'package:hong_vpn_new_20240626/utils/Configs/color_config.dart';
import 'package:hong_vpn_new_20240626/utils/Configs/text_style_config.dart';
import 'package:hong_vpn_new_20240626/utils/models/ai_model.dart';
import 'package:hong_vpn_new_20240626/utils/utils.dart';

import '../../utils/zz_navigator.dart';
import '../setting/setting.dart';

class HomeWidget extends StatefulWidget {
  const HomeWidget({super.key});

  @override
  State<HomeWidget> createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  int selectedIndex = 0;

  List<AiModel> aimodels = [];

  @override
  void initState() {
    super.initState();

    eventBus.on<AiLikedChanged>().listen((e) {
      _reloadAiChat();
      zzLog("fdafdasfdasfds");
    });
    eventBus.on<AiChatsChanged>().listen((e) {
      mounted ? setState(() {}) : null;
    });

    _reloadAiChat();
  }

  _reloadAiChat() async {
    aimodels = await AiConfig.cacheModels();
    mounted ? setState(() {}) : null;
  }

  _aiChatTap(int index) {
    var item = aimodels[index];
    ZZNavigator.push(widget: AiDetailsWidget(model: item));
  }

  _chatsTap(int index) {
    var item = AiConfig.chats[index];
    ZZNavigator.push(
        widget: ChatWidget(
      model: item,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home"),
        actions: [
          IconButton(
              onPressed: () => ZZNavigator.push(widget: const SettingWidget()),
              icon: const Icon(Icons.settings))
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(15),
            child: Row(
              children: [
                Expanded(
                    child: TextButton.icon(
                  onPressed: () =>
                      ZZNavigator.push(widget: const IndexWidget()),
                  label: const Text(
                    "Network",
                    style: TextStyle(fontSize: 20, color: Colors.white),
                  ),
                  icon: Image.asset("assets/images/网络.png"),
                  style: ButtonStyle(
                      padding: const WidgetStatePropertyAll(EdgeInsets.all(20)),
                      shape: const WidgetStatePropertyAll(
                          RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10)))),
                      backgroundColor: WidgetStatePropertyAll(
                          Colors.white.withOpacity(0.1))),
                )),
                const SizedBox(width: 15),
                Expanded(
                    child: TextButton.icon(
                  onPressed: () =>
                      ZZNavigator.push(widget: const ScanQRWidget()),
                  label: const Text(
                    "Scan QR",
                    style: TextStyle(fontSize: 20, color: Colors.white),
                  ),
                  icon: Image.asset("assets/images/扫一扫.png"),
                  style: ButtonStyle(
                    padding: const WidgetStatePropertyAll(EdgeInsets.all(20)),
                    side: WidgetStatePropertyAll(
                        BorderSide(color: Colors.white.withOpacity(0.4))),
                    shape: const WidgetStatePropertyAll(RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10)))),
                  ),
                ))
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            height: 75,
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: [
                TextButton(
                  onPressed: () {
                    selectedIndex = 0;
                    setState(() {});
                  },
                  style: ButtonStyle(
                    backgroundColor: WidgetStatePropertyAll(selectedIndex == 0
                        ? ColorConfig.orange
                        : Colors.white.withOpacity(0.05)),
                    padding: const WidgetStatePropertyAll(
                        EdgeInsets.only(left: 30, right: 30)),
                    shape: const WidgetStatePropertyAll(RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10)))),
                  ),
                  child: const Text(
                    "AI Chat",
                    style: TextStyle(fontSize: 20, color: Colors.white),
                  ),
                ),
                const SizedBox(width: 15),
                TextButton(
                  onPressed: () {
                    selectedIndex = 1;
                    setState(() {});
                  },
                  style: ButtonStyle(
                    backgroundColor: WidgetStatePropertyAll(selectedIndex == 1
                        ? ColorConfig.orange
                        : Colors.white.withOpacity(0.05)),
                    padding: const WidgetStatePropertyAll(
                        EdgeInsets.only(left: 30, right: 30)),
                    shape: const WidgetStatePropertyAll(RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10)))),
                  ),
                  child: const Text(
                    "Chat",
                    style: TextStyle(fontSize: 20, color: Colors.white),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: selectedIndex == 0 ? aiChat() : chats(),
          )
        ],
      ),
    );
  }

  Widget aiChat() {
    var cont = MediaQuery.of(context);
    var itemH = (cont.size.width - 45.0) / 2.0 + 44;
    return GridView.builder(
      padding:
          EdgeInsets.only(left: 15, right: 15, bottom: cont.padding.bottom),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 15,
          crossAxisSpacing: 15,
          mainAxisExtent: itemH),
      itemCount: aimodels.length,
      itemBuilder: (BuildContext context, int index) {
        var item = aimodels[index];
        return GestureDetector(
          onTap: () => _aiChatTap(index),
          child: Column(
            children: [
              AspectRatio(
                aspectRatio: 1,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.asset(
                      item.header ?? "assets/images/Rectangle 49.png"),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 10, bottom: 10),
                child: Row(
                  children: [
                    Text(
                      item.title ?? "",
                      style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500),
                    ),
                    const Spacer(),
                    Image.asset(item.isLike
                        ? "assets/images/点赞爱心.png"
                        : "assets/images/爱心点赞.png"),
                    const SizedBox(width: 5),
                    Text(
                      item.likeNumFormatter,
                      style: const TextStyle(color: Colors.white, fontSize: 14),
                    ),
                  ],
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Widget chats() {
    if (AiConfig.chats.isEmpty) {
      return Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.only(bottom: 100),
        child: Text(
          "Nothing Chats",
          style: TextStyleConfig.bold.copyWith(fontSize: 18),
        ),
      );
    }
    var cont = MediaQuery.of(context);
    return ListView.separated(
        padding:
            EdgeInsets.only(left: 15, right: 15, bottom: cont.padding.bottom),
        itemBuilder: (context, index) {
          var item = AiConfig.chats[index];
          return GestureDetector(
            onTap: () => _chatsTap(index),
            child: Padding(
                padding: const EdgeInsets.only(left: 10, right: 10),
                child: Row(
                  children: [
                    ClipOval(
                      child: Image.asset(
                        item.header ?? "assets/images/Rectangle 49.png",
                        width: 50,
                      ),
                    ),
                    const SizedBox(width: 10),
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item.title ?? "",
                          style: const TextStyle(
                              color: Colors.white, fontSize: 16),
                        ),
                        Text(
                          item.description,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                              color: Colors.white60, fontSize: 14),
                        ),
                      ],
                    ))
                  ],
                )),
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            color: Colors.white.withOpacity(0.4),
            thickness: 0.5,
          );
        },
        itemCount: AiConfig.chats.length);
  }
}
